﻿using System;
using System.CodeDom;
using System.Web.Compilation;
using System.Web.UI;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using SharePointOfView.Utilities;

namespace SharePointOfView.ExpressionBuilders
{
    [ExpressionEditor(typeof(ResourcesExpressionEditor))]
    public class ResourcesExpressionBuilder : System.Web.Compilation.ExpressionBuilder
    {
        public override object EvaluateExpression(object target, BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
        {
            return GetResources(parsedData.ToString());
        }

        public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
        {
            CodePrimitiveExpression prim = new CodePrimitiveExpression(parsedData as String);
            CodeExpression[] args = { prim };
            CodeTypeReferenceExpression refType = new CodeTypeReferenceExpression(this.GetType());

            return new CodeMethodInvokeExpression(refType, "GetResources", args);
        }

        public static string GetResources(string expression)
        {
            // Format : $SPResources:file,key
            string[] parts = expression.Split(',');
            string resKey = null;
            // Default resource file
            string translation = "";
            string resFile = null;
            switch (parts.Length)
            {
                case 1:
                    resKey = parts[0];
                    break;
                case 2:
                    resFile = parts[0];
                    resKey = parts[1];
                    break;
            }
            if (resKey != null)
            {
                translation = resKey.Trim();
                Localization loc = null;
                if (resFile == null)
                {
                    loc = new Localization(SPContext.Current.Web.Language);
                }
                else
                {
                    resFile = resFile.Trim();
                    loc = new Localization(resFile, SPContext.Current.Web.Language);
                }

                translation = loc.GetResource(resKey);
            }
            // Return translation
            return translation;
        }

        public override object ParseExpression(string expression, Type propertyType, ExpressionBuilderContext context)
        {
            return expression;
        }

        public override bool SupportsEvaluate
        {
            get
            {
                return true;
            }
        }
    }
}